<style lang="less">
  .ue-role {
    .el-select, .el-cascader {
      width: 100%
    }
    .fa-search,.fa-hand-pointer-o{
      color: #20a0ff;
      padding-right: 7px;
    }
    .column {
      display: flex;
      flex-direction: column;
      .el-table {
        overflow-y: auto;
        flex: 1;
      }
      .el-tree {
        overflow-y: auto;
        flex: 1;
      }
    }
    .fa-user{
      color: #20a0ff;
    }
  }
</style>

<template>
  <div class="columns ue-role">
    <div class="column">
      <el-col :span="24" style="margin-bottom: 10px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-col>
      <ue-el-tree-table
        height="100%"
        tree-structure
        tree-expand-all
        :data-source="treeData" highlight-current-row border
        @current-change="handleCurrentChange"
        v-loading="listLoading" style="width: 100%;">
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.type=='role'"

              @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
              v-if="scope.row.type=='role'"

              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </ue-el-tree-table>
    </div>
    <div class="column">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="addAuthority">保存</el-button>
      </div>
      <ue-el-tree
        ref="myTree"
        check-strictly
        :data="resourceTree"
        default-expand-all
        show-checkbox
        :chkboxType="{Y: 'ps',N: 's'}"
        node-key="id"
        :props="{children: 'children',label: 'name'}">
      </ue-el-tree>
    </div>
    <el-dialog :title="dialogTitle" size="tiny" :visible.sync="myFormVisible" :close-on-click-modal="false">
      <el-form :model="myForm" label-width="80px" ref="myForm">
        <el-form-item label="角色名"
                      :rules="[{ required: true, message: '请输入角色名', trigger: 'blur' },
                                     { max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }]"
                      prop="roleName">
          <el-input v-model="myForm.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="组织"
                      :rules="[{type:'array',required: true, message: '请选择组织', trigger: 'change' }]"
                      prop="pids">
          <el-cascader
            clearable
            :options="organizationTree"
            change-on-select
            :props="props"
            v-model="myForm.pids">
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="myFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="handleSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { saveRole, deleteRoles, orgRoleTree } from '../../api/organization/role';

import { organizationTree } from '../../api/organization/Organization';

export default {
  data () {
    return {
      props: {
        value: 'id',
        label: 'name'
      },
      myForm: {
        id: null,
        roleName: null,
        pids: [],
        organization: {
          id: null
        }
      },
      treeData: [],
      organizationTree: [],
      listLoading: false,
      resourceTree: [],
      dialogTitle: '',
      myFormVisible: false,
      selectedRole: null,
      selectOrgPids: []
    };
  },
  watch: {
    'myForm.pids': {
      deep: true,
      handler (val) {
        if (val.length > 0) {
          this.myForm.organization.id = val[val.length - 1];
        } else {
          this.myForm.organization.id = null;
        }
      }
    }
  },
  methods: {
    handleDelete (index, row) {
      this.$confirm('您确认删除该角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        deleteRoles(row.id).then(res => {
          if (res.data.successFlg) {
            this.reset();
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
      }).catch(() => {
      });
    },
    handleCurrentChange (val) {
      if (val) {
        if (val.type === 'role') {
          this.selectedRole = val;
          this.resourceTree = val.orgResourceTree;
          this.$ue.handleTreeItem(this.resourceTree, item => {
            if (item.type === 'BUTTON') {
              item.icon = 'fa fa-hand-pointer-o';
            } else if (item.type === 'QUERY') {
              item.icon = 'fa fa-search';
            }
          });
          this.selectOrgPids = [];
          this.$refs.myTree.setCheckedKeys(val.resourceIds);
        } else {
          this.selectedRole = null;
          this.resourceTree = [];
          this.selectOrgPids = Object.assign([], val.pids);
          this.selectOrgPids.push(val.id);
        }
      } else {
        this.selectedRole = null;
        this.resourceTree = [];
        this.selectOrgPids = [];
      }
    },
    addAuthority () {
      if (!this.selectedRole) {
        this.$message('请选择一个角色!');
        return;
      }
      let ids = this.$refs.myTree.getCheckedKeys(false);
      let resources = ids.map(item => {
        return {id: item};
      });
      saveRole({
        id: this.selectedRole.id,
        roleName: this.selectedRole.name,
        organization: {
          id: this.selectedRole.pid
        },
        resources: resources
      }).then(res => {
        if (res.data.successFlg) {
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
          this.reset();
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    reset () {
      this.loadOrgRoleTree();
      this.$refs.myTree.setCheckedKeys([]);
    },
    handleEdit (index, row) {
      if (this.$refs['myForm']) {
        this.$refs['myForm'].resetFields();
      }
      this.myForm.pids = row.pids;
      this.myForm.roleName = row.name;
      this.myForm.id = row.id;
      let resources = row.resourceIds.map(item => {
        return {id: item};
      });
      this.myForm.resources = resources;
      this.dialogTitle = '修改';
      this.myFormVisible = true;
    },
    handleAdd () {
      if (this.$refs['myForm']) {
        this.$refs['myForm'].resetFields();
      }
      this.myForm.resources = [];
      this.myForm.id = null;
      this.myForm.pids = this.selectOrgPids;
      this.myForm.roleName = null;
      this.dialogTitle = '添加';
      this.myFormVisible = true;
    },
    handleSubmit () {
      this.$refs['myForm'].validate((valid) => {
        if (valid) {
          saveRole(this.myForm).then(res => {
            if (res.data.successFlg) {
              this.myFormVisible = false;
              this.reset();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          });
        }
      });
    },
    loadOrgRoleTree () {
      this.listLoading = true;
      orgRoleTree().then(res => {
        if (res.data.successFlg) {
          this.treeData = res.data.detailModelList;
          this.$ue.handleTreeItem(this.treeData, item => {
            if (item.type === 'role') {
              item.icon = 'fa fa-user';
            }
          });
        } else {
          this.$message.error(res.data.errorMsg);
        }
        this.listLoading = false;
      });
    },
    loadOrganizationTree () {
      organizationTree().then(res => {
        if (res.data.successFlg) {
          this.organizationTree = res.data.detailModelList;
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    }
  },
  mounted () {
    this.loadOrgRoleTree();
    this.loadOrganizationTree();
  }
};
</script>
